/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * listSetor.java
 *
 * Created on 27/11/2011, 22:54:45
 */
package visao;

import EnderecoEstoque.EnderecoEstoque;
import fachada.FachadaBDR;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import setor.Setor;
import util.ErroAcessoRepositorioException;
import util.KeyValue;

/**
 *
 * @author Alberto
 */
public class listSetor extends javax.swing.JFrame {

    public String[] titulos = new String[]{"#", "Descrição Setor", "Endereço Setor", "QTD Maxima", "QTD Minima", "QTD Atual", "Sub Setor?", "Status"};
    public DefaultTableModel defTable;
    public CadSetor cadastroSetor = new CadSetor();

    /** Creates new form listSetor */
    public listSetor() {
        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            List<Setor> listSetor = objFachadaBDR.listarSetorAtivos();

            // Setando a tabela
            this.defTable = atualizaLista(listSetor);

        } catch (ErroAcessoRepositorioException ex) {
            System.out.println(ex.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        initComponents();
        this.setLocationRelativeTo(null);
        this.setIconImage(new ImageIcon(getClass().getResource("/Imagens/visao.gif")).getImage());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jComboBox_IdEndSetor = new javax.swing.JComboBox();
        jTextField_DescricaoSetor = new javax.swing.JTextField();
        bt_buscar = new javax.swing.JButton();
        jButton_Cadastrar = new javax.swing.JButton();
        jButton_Editar = new javax.swing.JButton();
        jButton_Atualizar = new javax.swing.JButton();
        jButton_Remover = new javax.swing.JButton();
        mensagem = new javax.swing.JLabel();

        setTitle("Setor");
        setResizable(false);

        jTable1.setModel(this.defTable);
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Descrição Setor:");

        jLabel2.setText("Endereço Setor:");

        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            List<EnderecoEstoque> listEndEstoque = objFachadaBDR.listarEnderecoEstoque("");

            jComboBox_IdEndSetor.addItem(new KeyValue("--- Favor Selecionar ---","0"));
            for (EnderecoEstoque objEndEstoque : listEndEstoque) {
                jComboBox_IdEndSetor.addItem(new KeyValue(objEndEstoque.getRuaEstoque(), Integer.toString(objEndEstoque.getIdEndereco())));
            }

        } catch (Exception e) {
        }

        bt_buscar.setText("Buscar");
        bt_buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_buscarActionPerformed(evt);
            }
        });

        jButton_Cadastrar.setText("Cadastrar");
        jButton_Cadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_CadastrarActionPerformed(evt);
            }
        });

        jButton_Editar.setText("Editar");
        jButton_Editar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_EditarActionPerformed(evt);
            }
        });

        jButton_Atualizar.setText("Atualizar");
        jButton_Atualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_AtualizarActionPerformed(evt);
            }
        });

        jButton_Remover.setText("Remover");
        jButton_Remover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_RemoverActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(8, 8, 8)
                                .addComponent(jLabel1)))
                        .addGap(24, 24, 24)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jComboBox_IdEndSetor, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jTextField_DescricaoSetor, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(bt_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(mensagem)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton_Cadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Editar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Atualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Remover, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 696, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(21, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jComboBox_IdEndSetor, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField_DescricaoSetor, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bt_buscar))
                .addGap(26, 26, 26)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE)
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_Cadastrar)
                    .addComponent(jButton_Editar)
                    .addComponent(jButton_Atualizar)
                    .addComponent(jButton_Remover))
                .addGap(18, 18, 18)
                .addComponent(mensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bt_buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_buscarActionPerformed
        try {
            // instanciando a fachada
            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();

            // Recuperendo os valores
            String descricaoSetor = jTextField_DescricaoSetor.getText();
            int idEnderecoEstoque = Integer.parseInt(((KeyValue) jComboBox_IdEndSetor.getSelectedItem()).getValue());

            // Listando as descrição produtos
            List<Setor> listSetor = objfaFachadaBDR.procurarSetorPorDescricaoPorEnderecoEstoque(descricaoSetor, idEnderecoEstoque);

            // Setando a tabela
            this.defTable = atualizaLista(listSetor);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);
            jTable1.revalidate();

            if (listSetor.size() > 0) {
                mensagem.setText("");
            } else {
                mensagem.setText("Nenhuma Sub Categoria encontrada!");
            }
        } catch (Exception ex) {
            mensagem.setText(ex.getMessage());
        }
    }//GEN-LAST:event_bt_buscarActionPerformed

    private void jButton_CadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CadastrarActionPerformed
        try {
            if (!this.cadastroSetor.isVisible()) {
                this.cadastroSetor = new CadSetor();
                this.cadastroSetor.setVisible(true);
            }
            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();
            List<Setor> listSetor = objfaFachadaBDR.listarSetorAtivos();

            // Setando a tabela
            this.defTable = atualizaLista(listSetor);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            jTable1.revalidate();
            mensagem.setText("");
        } catch (Exception ex) {
            mensagem.setText(ex.getMessage());
        }
    }//GEN-LAST:event_jButton_CadastrarActionPerformed

    private void jButton_EditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_EditarActionPerformed
        try {
            // pegando a linha selecionada
            if (this.jTable1.getSelectedColumnCount() == 0) {
                throw new Exception("Favor selecionar um Setor");
            }

            // Pegando a linha que está selecionada
            int linha = this.jTable1.getSelectedRow();
            // recuperando o Cpf do funcionario
            int idSetor = (Integer) this.jTable1.getValueAt(linha, 0);

            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();

            Setor objSetor = objfaFachadaBDR.procurarSetor(idSetor);

            // se a tela de cargo ja estiver instanciada
            if (!this.cadastroSetor.isVisible()) {
                this.cadastroSetor = new CadSetor(objSetor.getIdSetor());
                this.cadastroSetor.setVisible(true);
            }
            // Listando os cargos
            List<Setor> listSetor = objfaFachadaBDR.listarSetorAtivos();

            // Setando a tabela
            this.defTable = atualizaLista(listSetor);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            // atualizando os cargos
            jTable1.revalidate();

            mensagem.setText("");
        } catch (Exception ex) {
            mensagem.setText(ex.getMessage());
        }
    }//GEN-LAST:event_jButton_EditarActionPerformed

    private void jButton_AtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AtualizarActionPerformed
        try {
            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();

            // Listando os cargos
            List<Setor> listSetor = objfaFachadaBDR.listarSetorAtivos();

            // Setando a tabela
            this.defTable = atualizaLista(listSetor);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            // atualizando os cargos
            jTable1.revalidate();

            mensagem.setText("");
        } catch (Exception ex) {
            mensagem.setText(ex.getMessage());
        }
    }//GEN-LAST:event_jButton_AtualizarActionPerformed

    private void jButton_RemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_RemoverActionPerformed
        try {
            // pegando a linha selecionada
            if (this.jTable1.getSelectedColumnCount() == 0 || this.jTable1.getSelectedColumnCount() > 1) {
                throw new Exception("Favor selecionar um Setor");
            }

            int cancelar = JOptionPane.showConfirmDialog(null, "Deseja Remover este Setor?");
            if (cancelar == JOptionPane.YES_OPTION) {
                try {
                    int linha = this.jTable1.getSelectedRow();

                    // recuperando o Cpf do funcionario
                    int idSetor = (Integer) this.jTable1.getValueAt(linha, 0);

                    // instanciando a fachada
                    FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();

                    // Listando os cargos
                    objfaFachadaBDR.removerSetor(idSetor);

                    // Listando os cargos
                    List<Setor> listSetor = objfaFachadaBDR.listarSetorAtivos();

                    // Setando a tabela
                    this.defTable = atualizaLista(listSetor);

                    // Setando a nova listagem
                    jTable1.setModel(this.defTable);

                    jTable1.revalidate();

                    mensagem.setText("Removido com sucesso!");

                } catch (Exception ex) {
                    mensagem.setText(ex.getMessage());
                }
            }
        } catch (Exception e) {
            mensagem.setText(e.getMessage());
        }
    }//GEN-LAST:event_jButton_RemoverActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new listSetor().setVisible(true);
            }
        });
    }

    public DefaultTableModel atualizaLista(List<Setor> listSetor) {
        // {"#", "Descrição Setor", "Endereço Setor", "QTD Maxima", "QTD Minima", "QTD Atual", "Sub Setor?","Status"}
        // Criando o objeto 
        Object[][] resposta = new Object[listSetor.size()][8];

        for (int i = 0; i < resposta.length; i++) {
            Setor objSetor = listSetor.get(i);
            resposta[i][0] = objSetor.getIdSetor();
            resposta[i][1] = objSetor.getDescricaoSetor();
            resposta[i][2] = objSetor.getEnderecoEstoque().getRuaEstoque();
            resposta[i][3] = objSetor.getQuantidadeMaxima();
            resposta[i][4] = objSetor.getQuantidadeMinima();
            resposta[i][5] = objSetor.getQuantidadeArmazenada();
            resposta[i][6] = (objSetor.getFlagSubSetor()) ? "Sim" : "Não";
            resposta[i][7] = (objSetor.getStatusSetor()) ? "Ativo" : "Inativo";
        }

        // Setando a tabela
        return new DefaultTableModel(resposta, titulos);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_buscar;
    private javax.swing.JButton jButton_Atualizar;
    private javax.swing.JButton jButton_Cadastrar;
    private javax.swing.JButton jButton_Editar;
    private javax.swing.JButton jButton_Remover;
    private javax.swing.JComboBox jComboBox_IdEndSetor;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField_DescricaoSetor;
    private javax.swing.JLabel mensagem;
    // End of variables declaration//GEN-END:variables
}
